<template>
	<view class="alarm-container">
		<!-- 顶部标题和搜索区域 -->
		<view class="header">
			<!-- 常规标题栏 -->
			<view class="title-bar" v-if="!isSearchMode">
				<text class="title">告警消息</text>
				<view class="header-actions">
					<image 
						src="/static/images/filter.svg" 
						class="filter-icon" 
						mode="aspectFit"
						@tap="goToAlarmSearch"
					></image>
					<image 
						src="/static/images/search.svg" 
						class="search-icon" 
						mode="aspectFit" 
						@tap="toggleSearch"
					></image>
				</view>
			</view>
			
			<!-- 搜索模式标题栏 -->
			<view class="search-header" v-else>
				<view class="search-left">
					<image 
						src="/static/images/back.svg" 
						class="back-icon" 
						mode="aspectFit" 
						@tap="toggleSearch"
					></image>
				</view>
				<view class="search-content">
					<input 
						type="text"
						class="search-input"
						v-model="textSearch"
						placeholder="请输入告警名称"
						placeholder-class="search-placeholder"
						@input="onKeyInput"
						confirm-type="search"
						focus
					/>
					<image 
						v-if="textSearch"
						src="/static/images/clear.svg" 
						class="clear-icon" 
						mode="aspectFit"
						@tap="clearSearch"
					></image>
				</view>
			</view>
		</view>
		
		<!-- 修改 scroll-view 的样式类 -->
		<scroll-view 
			class="alarm-scroll"
			scroll-y="true"
			@scrolltolower="loadMore"
			@refresherrefresh="onRefresh"
			:refresher-enabled="true"
			:refresher-triggered="isRefreshing"
		>
			<!-- 添加一个容器来包裹所有卡片 -->
			<view class="alarm-list">
				<!-- 当没有数据时显示空状态 -->
				<view v-if="alarmList.length === 0 && !isLoading" class="empty-state">
					<image 
						src="/static/images/no-data.svg" 
						mode="aspectFit" 
						class="empty-image"
					></image>
					<text class="empty-text">暂无告警数据</text>
				</view>
				
				<!-- 告警列表 -->
				<template v-else>
					<view class="alarm-card" v-for="(alarm, index) in alarmList" :key="index">
						<!-- 左侧红色指示条 -->
						<view class="alarm-indicator" :class="getSeverityClass(alarm.severity)"></view>
						
						<!-- 告警内容 -->
						<view class="alarm-content">
							<view class="alarm-header">
								<text class="alarm-name">{{ alarm.name }}</text>
								<text class="alarm-time">{{ formatTime(alarm.createdTime) }}</text>
							</view>
							<view class="device-info">
								<text class="alarm-device">{{ alarm.originatorName }}</text>
								<view class="severity-tag" :class="getSeverityClass(alarm.severity)">
									{{ getSeverityText(alarm.severity) }}
								</view>
							</view>
							<view class="divider"></view>
							<view class="alarm-footer">
								<text class="alarm-status">{{ getStatusText(alarm.status) }}</text>
								<view class="more-btn" @tap="goToAlarmDetail(alarm)">
									<view class="dot"></view>
									<view class="dot"></view>
									<view class="dot"></view>
								</view>
							</view>
						</view>
					</view>
					
					<!-- 加载状态 -->
					<view v-if="isLoading" class="loading-more">
						<text>加载中...</text>
					</view>
					
					<!-- 没有更多数据 -->
					<view v-if="!hasMore && alarmList.length > 0" class="no-more">
						<text>没有更多数据了</text>
					</view>
				</template>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import request from '@/utils/request.js'
import { formatTime } from '@/utils/timeUtils.js'

	export default {
		data() {
			return {
			alarmList: [],
			page: 0,
			pageSize: 10,
			textSearch: '',
			sortProperty: 'createdTime',
			sortOrder: 'DESC',
			statusList: ['ACTIVE'],
			severityList: [],
			typeList: [],
			assigneeId: null,
			hasMore: true,
			isRefreshing: false,
			isLoading: false,
			isSearchMode: false,
			searchTimer: null,
			needRefresh: false,  // 添加刷新标记
			// 添加筛选条件的存储
			filterConditions: {
				statusList: ['ACTIVE'],
				severityList: [],
				typeList: [],
				assigneeId: null
			}
		}
	},
	onLoad() {
		this.fetchAlarms()
	},
	onShow() {
		// 如果需要刷新，则重新加载告警列表
		if (this.needRefresh) {
			this.alarmList = []  // 清空现有数据
			this.page = 1      // 重置页码
			this.hasMore = true  // 重置加载更多状态
			this.fetchAlarms(true)  // 重新加载数据
			this.needRefresh = false  // 重置刷新标记
		}
	},
	methods: {
		// 移除本地的 formatTime 方法，改用导入的方法
		formatTime,
		
		// 获取告警数据
		async fetchAlarms(isRefresh = false) {
			if (this.isLoading) return
			
			try {
				this.isLoading = true
				
				// 构建请求参数
				const params = {
					pageSize: this.pageSize,
					page: this.page,
					textSearch: this.textSearch,
					sortProperty: this.sortProperty,
					sortOrder: this.sortOrder,
					statusList: this.statusList,
					severityList: this.severityList,
					typeList: this.typeList,
					assigneeId: this.assigneeId
				}
				
				// 移除空值参数
				Object.keys(params).forEach(key => {
					if (Array.isArray(params[key]) && params[key].length === 0) {
						delete params[key]
					} else if (params[key] === null || params[key] === undefined || params[key] === '') {
						delete params[key]
					}
				})
				
				const result = await request.get('/api/v2/alarms', params)
				
				if (result && result.data) {
					if (isRefresh) {
						this.alarmList = result.data
					} else {
						this.alarmList = [...this.alarmList, ...result.data]
					}
					this.hasMore = result.hasNext || false
				}
			} catch (error) {
				console.error('Failed to fetch alarms:', error)
				uni.showToast({
					title: '获取告警失败',
					icon: 'none'
				})
			} finally {
				this.isLoading = false
				if (isRefresh) {
					this.isRefreshing = false
					uni.stopPullDownRefresh()
				}
			}
		},
		
		// 搜索处理
		handleSearch() {
			this.page = 0
			this.fetchAlarms(true)
		},
		
		// 下拉刷新
		async onRefresh() {
			if (this.isRefreshing || this.isLoading) return
			this.isRefreshing = true
			this.page = 0
			await this.fetchAlarms(true)
		},
		
		// 上拉加载更多
		async loadMore() {
			if (!this.hasMore || this.isLoading || this.isRefreshing) return
			this.page++
			await this.fetchAlarms()
		},
		
		// 根据 severity 返回对应的样式类名
		getSeverityClass(severity) {
			const severityMap = {
				'CRITICAL': 'severity-critical',
				'MAJOR': 'severity-major',
				'MINOR': 'severity-minor',
				'WARNING': 'severity-warning',
				'INDETERMINATE': 'severity-indeterminate'
			}
			return severityMap[severity] || 'severity-default'
		},
		
		// 切换搜索模式
		toggleSearch() {
			if (this.isSearchMode) {
				this.isSearchMode = false
				this.textSearch = ''
				this.page = 0
				this.fetchAlarms(true)
			} else {
				this.isSearchMode = true
			}
		},

		// 处理输入事件
		onKeyInput(event) {
			// 清除之前的定时器
			if (this.searchTimer) {
				clearTimeout(this.searchTimer)
			}
			
			// 设置新的定时器，延迟300ms执行搜索
			this.searchTimer = setTimeout(() => {
				this.textSearch = event.detail.value
				this.page = 0  // 重置页码
				this.fetchAlarms(true)  // 执行搜索
			}, 300)
		},
		
		// 清除搜索内容
		clearSearch() {
			this.textSearch = ''
			this.page = 0
			this.fetchAlarms(true)
		},
		
		// 获取告警状态文本
		getStatusText(status) {
			const statusMap = {
				'ACTIVE_ACK': '激活已确认',
				'ACTIVE_UNACK': '激活未确认',
				'CLEARED_ACK': '清除已确认',
				'CLEARED_UNACK': '清除未确认'
			}
			return statusMap[status] || status
		},
		
		// 获取告警级别文本
		getSeverityText(severity) {
			const severityMap = {
				'CRITICAL': '严重',
				'MAJOR': '重要',
				'MINOR': '次要',
				'WARNING': '警告',
				'INDETERMINATE': '未定'
			}
			return severityMap[severity] || severity
		},
		
		// 修改跳转到告警搜索页面的方法
		goToAlarmSearch() {
			uni.navigateTo({
				url: '/pages/alarm/alarmSearch',
				success: (res) => {
					// 传递当前的筛选条件
					res.eventChannel.emit('filterConditions', this.filterConditions)
				},
				events: {
					// 接收告警搜索页面返回的筛选条件
					acceptAlarmSearchConditions: (data) => {
						// 保存筛选条件
						this.filterConditions = data
						// 更新查询参数
						this.statusList = data.statusList || ['ACTIVE']
						this.severityList = data.severityList || []
						this.typeList = data.typeList || []
						this.assigneeId = data.assigneeId
						
						// 重置页码并重新加载数据
						this.page = 0
						this.alarmList = []
						this.hasMore = true
						this.fetchAlarms(true)
					}
				}
			})
		},
		
		// 重置筛选条件
		resetFilters() {
			this.statusList = ['ACTIVE']
			this.severityList = []
			this.typeList = []
			this.assigneeId = null
			this.page = 0
			this.alarmList = []
			this.hasMore = true
			this.fetchAlarms(true)
		},
		
		goToAlarmDetail(alarm) {
			uni.navigateTo({
				url: `/pages/alarm/alarmDetail?id=${alarm.id.id}&name=${encodeURIComponent(alarm.type)}`,
				events: {
					backToAlarmPage: (data) => {
						this.fetchAlarms(true)  // 重新加载数据
    				}
				}
			})
		}
		}
	}
</script>

<style>
.alarm-container {
	height: 100vh;
	background-color: #f5f5f5;
	display: flex;
	flex-direction: column;
}

.header {
	background-color: #fff;
	padding: 20rpx 30rpx;
	border-bottom: 1px solid #eee;
}

.title-bar,
.search-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.header-actions {
	display: flex;
	gap: 30rpx;
	align-items: center;
}

.filter-icon,
.search-icon {
	width: 40rpx;
	height: 40rpx;
	padding: 10rpx;
}

.alarm-scroll {
	flex: 1;
	width: 100%;
}

.alarm-list {
	padding: 20rpx;  /* 统一的内边距 */
	box-sizing: border-box;
}

.alarm-card {
	display: flex;
	background-color: #fff;
	margin-bottom: 20rpx;
	border-radius: 12rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.alarm-indicator {
	width: 8rpx;
}

.alarm-content {
	flex: 1;
	padding: 20rpx 30rpx;
}

.alarm-header {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 20rpx;
}

.alarm-name {
	font-size: 32rpx;
	color: #333;
	flex: 1;
	font-weight: 600;
}

.alarm-time {
	font-size: 28rpx;
	color: #999;
}

.device-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 15rpx;
	padding: 5rpx 0;
}

.alarm-device {
	font-size: 28rpx;
	color: #666;
}

.severity-tag {
	padding: 4rpx 12rpx;
	border-radius: 4rpx;
	font-size: 26rpx;
	color: #fff;
}

.divider {
	height: 1px;
	background-color: #eee;
	margin: 0 -30rpx 15rpx -30rpx;
}

.alarm-footer {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 10rpx 0;
	min-height: 60rpx;
}

.alarm-status {
	font-size: 26rpx;
	color: #305680;
	background-color: rgba(48, 86, 128, 0.08);
	padding: 6rpx 16rpx;
	border-radius: 6rpx;
	font-weight: 500;
	letter-spacing: 1rpx;
	display: inline-block;
	line-height: 1.4;
}

.more-btn {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	gap: 6rpx;
	width: 56rpx;
	height: 56rpx;
	border-radius: 50%;
	background-color: #F3F5F8;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	position: relative;
	margin: 6rpx;
}

.more-btn:active {
	background-color: #E8EBF0;
}

.dot {
	width: 6rpx;
	height: 6rpx;
	border-radius: 50%;
	background-color: #305680;
}

.loading-more, .no-more {
	text-align: center;
	padding: 20rpx;
	color: #999;
	font-size: 24rpx;
}

/* Severity 相关样式 */
.severity-critical {
	background-color: #FF4D4F;
}

.severity-major {
	background-color: #FF7A45;
}

.severity-minor {
	background-color: #FFA940;
}

.severity-warning {
	background-color: #FAAD14;
}

.severity-indeterminate {
	background-color: #008000;
}

.severity-default {
	background-color: #999;
}

/* 文字颜色只应用于 alarm-severity */
.alarm-severity {
	display: none;
}

.search-left {
	display: flex;
	align-items: center;
}

.back-icon {
	width: 40rpx;
	height: 40rpx;
	padding: 10rpx;
}

.search-content {
	flex: 1;
	display: flex;
	align-items: center;
	margin-left: 30rpx;
	position: relative;
}

.clear-icon {
	width: 32rpx;
	height: 32rpx;
	padding: 10rpx;
	position: absolute;
	right: 20rpx;
	top: 50%;
	transform: translateY(-50%);
}

.search-input {
	flex: 1;
	height: 60rpx;
	font-size: 32rpx;
	color: #333;
	padding-right: 70rpx;
}

.search-placeholder {
	color: #999;
	font-size: 32rpx;
}

/* 添加响应式布局 */
@media screen and (min-width: 768px) {
	.alarm-list {
		padding: 30rpx;
	}
	
	.alarm-card {
		margin-bottom: 30rpx;
	}
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.empty-image {
	width: 240rpx;
	height: 240rpx;
	margin-bottom: 30rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
}

.loading-more, 
.no-more {
	text-align: center;
	padding: 30rpx 0;
	color: #999;
	font-size: 24rpx;
}
</style>
